<template>
  <div class="chat-cell-content" ref="scrollContainer">
    <chat-cell v-for="(item, index) in historyList" :key="item.messageId" :msgContent="item" ref='chatHistory'>
      <chat-cell-tool @copyText="copyText('history',index)"></chat-cell-tool>
    </chat-cell>

    <chat-cell v-for="(item, index) in messageList" :key="item.messageId" :msgContent="item" ref='chatMessage'>
      <chat-cell-tool @copyText="copyText('message',index)"></chat-cell-tool>
    </chat-cell>

    <chat-cell :msgContent="handleMessage" v-show="handleMessage?.messageId" ref='chatHandle'>
      <chat-cell-tool @copyText="copyText('handle')" @reAnswer="reAnswer" :isShowAnswer="isShowAnswer" v-show='isShowAnswer'></chat-cell-tool>
    </chat-cell>
  </div>
</template>

<script lang="ts" setup>
import { ref, defineProps, watchEffect, onMounted, watch, nextTick, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import {useClipboard } from '@vueuse/core'
import { type AIAgent, type UserInfo, type ChatMessage, AIGCStatus } from '../../utils/interface'
import ChatCell from './ChatCell.vue'
import ChatCellTool from './ChatCellTool.vue'
import { ChatSession } from '../../utils/chat-session'
import { AIGCSession } from '../../utils/aigc-session'
import { aiAgentStore } from '../../stores/ai-agent'
import EnvConfig from '../../utils/config'
const agentStore = aiAgentStore()
const historyList = ref<ChatMessage[]>([])
const handleMessage = ref<any>({})
const messageList = ref<any>([])
const conversionInfo = ref({})
const scrollContainer = ref<HTMLFormElement | null>(null) as any
const props = defineProps({
  conversionInfo: {
    type: Object,
    default: () => {}
  },
  chatInstance: {
    type: Object,
    default: () => {}
  },
  aigcInstance: {
    type: Object,
    default: () => {}
  },
  historyMessageList: {
    type: Array,
    default: () => []
  },
  handleMessage: {
    type: Object,
    default: () => {}
  },
  messageList: {
    type: Array,
    default: () => []
  }
})
const isShowAnswer = ref(false)
const chatHistory = ref()
const chatMessage = ref()
const chatHandle = ref()
const elementItem = reactive({
  "history": chatHistory,
  "message": chatMessage,
  "handle": chatHandle
})
onMounted(() => {
  // console.log(historyList.value,"get historyList data")
  // console.log(historyMessageList,handleMessage,".......2020202")
  // const agentInfo = EnvConfig?.chat_become_home ? props?.conversionInfo?.agentInfo : agentStore.myAgents[0];
  // const conversionId = EnvConfig?.chat_become_home ? props.conversionInfo?.conversionId : '';
  // console.log(props.conversionInfo,ChatSession,"00000")
  // const chatSession: ChatSession = new ChatSession(agentInfo,conversionId, true)
  // const aigcSession:AIGCSession = new AIGCSession(agentInfo,conversionId, true, ()=>{})
  //获取历史消息
  // chatSession.getMessageHistory({conversionId:conversionId})
  // watchEffect(() => {
  //     if(chatSession?.historyMessageList){
  //         historyMessageList.value = chatSession?.historyMessageList || []
  //     }
  // });
  // handleMessage.value = aigcSession?.handleMessage || []
  // watchEffect(() => {
  //     if(aigcSession?.handleMessage){
  //         handleMessage.value = [...aigcSession?.handleMessage]
  //     }
  // });
  // watchEffect(() => {
  //     if(props?.historyMessageList){
  //         console.log(props.historyMessageList,"change historyMessageList")
  //     }
  // });
})

//重新回答
const reAnswer = () =>{
  if(props?.chatInstance){
    props?.chatInstance?.aicgSession?.reAsk()
  }
}

//复制
const copyText = async (item:any,index?:number) => {
  let cellDom = item === "handle" ? elementItem[item] : elementItem[item][index];
  const textHtml = cellDom.cellDom;
  const text = textHtml.textContent || '';
  console.log(cellDom,textHtml,text,"111")
  // const { copy, isSupported } = useClipboard({
  //     source: decodeURIComponent(text),
  //     read: false,
  // })
  // if (!isSupported.value) {
  //   ElMessage('当前浏览器不支持复制');
  //   return
  // }
  // try {
  //     await copy()
  //     ElMessage.success('复制成功')
  // } catch (e: any) {
  //     ElMessage.error('复制失败')
  // }
  
  const input = document.createElement('input')
  input.setAttribute('value', text)
  document.body.appendChild(input)
  input.select()
  input.setSelectionRange(0,text.length); //兼容ios-safari核心代码
  document.execCommand('Copy')
  document.body.removeChild(input);
  ElMessage.success('复制成功')
}

watch(
  () => props?.chatInstance?.aicgSession?.status,
  (val, oldVal) => {
    if(val?.value === AIGCStatus.Completed){
      isShowAnswer.value = true;
    }
    else{
      isShowAnswer.value = false;
    }
  },
  {
    deep: true,
    immediate: true
  }
)

watch(
  () => props?.handleMessage,
  (val, oldVal) => {
    handleMessage.value = val || {}
    nextTick(() => {
      scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight;
    })
  },
  {
    deep: true,
    immediate: true
  }
)

watch(
  () => props?.historyMessageList,
  (val, oldVal) => {
    historyList.value = val || []
    nextTick(() => {
      scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight
    })
  },
  {
    deep: true,
    immediate: true
  }
)

watch(
  () => props?.messageList,
  (val, oldVal) => {
    messageList.value = val || []
    nextTick(() => {
      scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight
    })
  },
  {
    deep: true,
    immediate: true
  }
)
</script>

<style scoped lang="scss">
.chat-cell-content {
  overflow: auto; /* 保持可滚动 */
  scrollbar-width: none;
  height: 100%;
}
</style>
